<template>
  <view class="flex flex-col h-screen issue">
    <u-navbar auto-back placeholder safe-area-inset-top/>
    <step :current="stepCurrent" class="flex-1 bg-white" @finish="handlerStepFinish">
      <cus-step-item title="基础信息">
        <view class="p-10px">
          <u-form label-position="top" label-width="auto" :model="formData">
            <u-form-item label="书籍名称" prop="name">
              <u-input v-model="formData.name" placeholder="请输入书籍名称"/>
            </u-form-item>
            <u-form-item label="书籍简介" prop="intro">
              <u-input v-model="formData.intro" placeholder="请输入书籍简介"/>
            </u-form-item>
            <u-form-item label="购买价格" prop="old_price">
              <u-input v-model="formData.oldPrice" placeholder="请输入书籍名称"/>
            </u-form-item>
            <u-form-item label="购买时间" prop="shop_time">
              <!--              <u-datetime-picker v-model="formData.shopTime" model="date" placeholder="请选择书籍购买时间"/>-->
              <view @click.stop="handlerShopTimeInputFocus">
                <template v-if="formData.shopTime">
                  {{ compShopTimeText }}
                </template>
                <template v-else>
                  <text class="text-hex-3c9cff">
                    点击选择购买时间
                  </text>
                </template>
              </view>
              <u-datetime-picker title="选择购买时间" v-model="shopTimePickerValue" mode="date" :show="shopTimeVisible" placeholder="请选择书籍购买时间" @confirm="handlerShopTimeConfirm" @cancel="handlerStopTimeCancel" :max-date="new Date().getTime()"/>
            </u-form-item>
            <u-form-item label="书籍标签">
              <tag-select v-model="selectTag" :tag-list="tagList" @insert="handlerTagInsert" />
            </u-form-item>
            <u-form-item label="购买时的图片" prop="old_imags">
<!--              <u-input placeholder="请输入书籍名称"/>-->
              <qiniu-img-upload type="upload" v-model="oldImgs"/>
            </u-form-item>
          </u-form>
        </view>
      </cus-step-item>
      <cus-step-item title="出售信息">
        <view class="p-10px">
          <u-form label-position="top" label-width="auto" :model="formData">
            <u-form-item label="标题（书籍列表中展示的标题内容）" prop="name">
              <u-input v-model="formData.title" placeholder="请输入书籍标题信息"/>
            </u-form-item>
            <u-form-item label="售价" prop="price">
              <u-input v-model="formData.price" placeholder="请输入书籍售价"/>
            </u-form-item>
            <u-form-item label="图片" prop="imgs">
              <template #label>
                <text>图片</text>
                <text class="text-12px text-">(默认以第一张作为封面)</text>
              </template>
<!--              <u-upload/>-->
              <qiniu-img-upload type="upload" v-model="imgs"/>
            </u-form-item>
            <u-form-item label="说明" prop="explain">
              <u-textarea v-model="formData.explain" placeholder="输入书籍备注信息"/>
            </u-form-item>
          </u-form>
        </view>
      </cus-step-item>
    </step>
    <u-toast ref="uToast"/>
  </view>
  <u-overlay :show="overlayShow">
    <template v-if="issueState === 0">
      <view class="absolute top-1_2 left-1_2 transform -translate-x-1_2 -translate-y-1_2 text-hex-efefef">
        <u-loading-icon mode="semicircle" color="#efefef" size="80rpx"/>
      </view>
    </template>
    <template v-else-if="issueState === 1">
      <view class="absolute top-1_2 left-1_2 transform -translate-x-1_2 -translate-y-1_2 text-hex-efefef">
        <view class="text-center">
          <u-icon name="checkmark" class="inline-block margin-auto" size="80rpx" color="#efefef"/>
        </view>
        <view class="text-center text-30rpx">
          发布成功
        </view>
      </view>
    </template>
    <template v-else-if="issueState === 2">
      <view class="absolute top-1_2 left-1_2 transform -translate-x-1_2 -translate-y-1_2 text-hex-efefef">
        <view class="text-center">
          <u-icon name="close" class="inline-block margin-auto" size="80rpx" color="#efefef"/>
        </view>
        <view class="text-center text-30rpx">
          发布失败
        </view>
      </view>
    </template>
  </u-overlay>
</template>

<script setup lang="ts">
import {computed, reactive, ref} from 'vue'
import UNavbar from "@/uni_modules/uview-plus/components/u-navbar/u-navbar.vue";
import Step from '@/components/Step'
import CusStepItem from '@/components/Step/item.vue'
import UForm from "@/uni_modules/uview-plus/components/u-form/u-form.vue";
import UFormItem from "@/uni_modules/uview-plus/components/u-form-item/u-form-item.vue";
import UInput from "@/uni_modules/uview-plus/components/u--input/u--input.vue";
import UDatetimePicker from "@/uni_modules/uview-plus/components/u-datetime-picker/u-datetime-picker.vue";
import QiniuImgUpload from "@/components/qiniu-img-upload.vue";
import type { BookInsBody } from "@/api/book";
import {getBookById, insertBook, updateBook} from "@/api/book";
import dayjs from "dayjs";
import TagSelect from "@/components/tagSelect.vue";
import type { Tag } from "@/components/types";
import {getBookType, postInsertBookType} from "@/api/bookType";
import UTextarea from "@/uni_modules/uview-plus/components/u--textarea/u--textarea.vue";
import UToast from "@/uni_modules/uview-plus/components/u-toast/u-toast.vue";
import UOverlay from "@/uni_modules/uview-plus/components/u-overlay/u-overlay.vue";
import ULoadingIcon from "@/uni_modules/uview-plus/components/u-loading-icon/u-loading-icon.vue";
import UIcon from "@/uni_modules/uview-plus/components/u-icon/u-icon.vue";
import {onLoad} from "@dcloudio/uni-app";

// 就图片地址
const oldImgs = ref<string[]>([])
// 销售图片
const imgs = ref<string[]>([])

const stepCurrent = ref<number>(0)
// 消息提示弹窗
const uToast = ref<UToast>(null)
// 表单输入结果
const formData = reactive<BookInsBody>({
  name: '',
  title: '',
  intro: '',
  price: null,
  imgs: '',
  oldPrice: null,
  oldImgs: '',
  shopTime: null,
  bTypes: '',
  explain: ''
})
// 步骤条组件点击完成
const handlerStepFinish = () => {
  // 将图片拼接成字符串
  formData.oldImgs = oldImgs.value.join(',')
  // 将销售信息里的图片拼接成字符串
  formData.imgs = imgs.value.join(',')
  // 将书籍标签拼接成字符串
  formData.bTypes = selectTag.value.map(item => item.value).join(',')
  console.log('selectTag', selectTag.value)
  if(pageState === 0){
    fnPostInsertBook()
  }else if(pageState === 1){
    fnPutUpdateBook()
  }
}
// 遮罩层显示状态
const overlayShow = ref(false)
// 发布状态(0:发布中，1：发布成功，2：发布失败）
const issueState = ref<0 | 1 | 2>(0)
const fnPostInsertBook = async () => {
  issueState.value = 0
  overlayShow.value = true
  try{
    const data = await insertBook(formData)
    if(data.code === 200){
      issueState.value = 1
      setTimeout(() => {
        overlayShow.value = false
        issueState.value = 0
        uni.navigateBack()
      }, 2000)
      return
    }
  }catch (e) {
    console.warn(e)
  }
  issueState.value = 2
}
const fnPutUpdateBook = async () => {
  issueState.value = 0
  overlayShow.value = true
  try{
    const data = await updateBook(formData)
    if(data.code === 200){
      issueState.value = 1
      setTimeout(() => {
        overlayShow.value = false
        issueState.value = 0
        uni.navigateBack()
      }, 2000)
      return
    }
  }catch (e) {
    console.warn(e)
  }
  issueState.value = 2
  setTimeout(() => {
    overlayShow.value = false
    issueState.value = 0
  }, 2000)
}

// 购买时间，时间选择器显示状态，默认不显示
const shopTimeVisible = ref(false)
const shopTimePickerValue = ref<number>(0)
const handlerShopTimeInputFocus = () => {
  shopTimeVisible.value = true;
}
const handlerShopTimeConfirm = (time: {value: number, mode: string}) => {
  formData.shopTime = new Date(time.value)
  shopTimeVisible.value = false
}
const compShopTimeText = computed(() => {
  if(formData.shopTime){
    return dayjs(formData.shopTime).format("YYYY-MM-DD")
  }
  return null
})
const handlerStopTimeCancel = () => {
  shopTimeVisible.value = false
}

// 书籍标签列表
const tagList = ref<Tag[]>([])
// 获取标签列表
const fnGetTagList = async () => {
  const { data } = await getBookType()
  tagList.value = data.map(item => {
    return {
      label: item.name,
      value: item.id
    }
  })
}
// 初始化标签列表
fnGetTagList()

// 选中的标签
const selectTag = ref<Tag[]>([])

const handlerTagInsert = async (label: string, callback: (value: Tag | null) => void) => {
  const tag = await fnPostInsertTag(label)
  if(tag){
    tagList.value.push(tag)
  }
  callback(tag)
}
// 新增tag标签的方法
const fnPostInsertTag = async (label: string): Promise<Tag | null> => {
  const { data, code = 500 } = await postInsertBookType({name: label})
  if(code === 200){
    return {
      label: data.name,
      value: data.id
    }
  }
  return null
}
let pageState: number = 0
const fnGetBookById = async (bId: number) => {
  const { data } = await getBookById(bId)
  oldImgs.value = data.oldImgs.split(",") || []
  imgs.value = data.imgs.split(",") || []
  selectTag.value = data.typeList.map(item => {
    return {
      label: item.name,
      value: item.id
    }
  })
  console.log('selectTag', selectTag.value)
  formData.bId = data.bid
  formData.intro = data.intro
  formData.name = data.name
  formData.price = data.price
  formData.shopTime = dayjs(data.shopTime).isValid() ? dayjs(data.shopTime).toDate() : null
  formData.bTypes = selectTag.value.map(item => item.value).join(",")
  formData.title = data.title
  formData.oldPrice = data.oldPrice
  formData.explain = data.explain
}
onLoad((options) => {
  if(options?.bid){
    pageState = 1
    return fnGetBookById(options.bid);
  }
  pageState = 0
})
</script>

<style lang="scss">
.issue{
}
</style>